;var scriptJSON = function (fullUrl) {
	this.fullUrl = fullUrl; 
	this.scriptId = 'scriptId' + this.scriptCounter++;
	this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
	this.documentHead = document.getElementsByTagName("head").item(0);	
};

scriptJSON.prototype = {
	constructor : scriptJSON,
	scriptCounter : 1,
	buildScriptTag : function () {
		this.scriptTag = document.createElement("script");
		this.scriptTag.setAttribute("type", "text/javascript");
		this.scriptTag.setAttribute("charset", "utf-8");
		this.scriptTag.setAttribute("src", this.fullUrl + this.noCacheIE);
		this.scriptTag.setAttribute("id", this.scriptId);
	},
	removeScriptTag : function () {
		this.documentHead.removeChild(this.scriptTag);  
	},
	addScriptTag : function () {
		this.documentHead.appendChild(this.scriptTag);
	}
};




OpenAuth = {
	//Do NOT rely on the default 'devId' here for prod deployment. Configure OpenAuthAPI with 
	//a prod-ready devId before going live (contact Kurt Moller (SNS team)). 
	
	config : { //internal default config values. 
		succUrl    		: window.config.openauth.urls.loggedin,
		logoutSuccURL  	: window.config.openauth.urls.loggedout,
		cookieName 		: "AOLTRAFFIC-AUTHTOKEN",
		devId	 		: window.config.openauth.devId, //visit dev.aol.com/keys to generate limited test devId's
		supportedIdType :  "SN,ICQ,OID"
	},
	
	getConfiguration : function(){
		return this.config;
	},
	
	hostname : function(){
		return location.protocol + "//" + location.host;
		//returns a string like->   "http://domain:8080"
	},
	
	configure : function(configdata) {
		configdata = configdata||{};
		var internalconfig = this.getConfiguration();
		for(var prop in configdata) {
			if(prop=="succUrl" || prop == "logoutSuccURL") {
				if(configdata[prop].indexOf("/")==0) {
					configdata[prop] = this.hostname() + configdata[prop];
				}
			};
			internalconfig[prop] = configdata[prop];
		};
	},
	
	requestID : function(){
		return (Math.round(Math.random()*10000000) + new Date().getTime().toString());	
	},
	
	addEventListener : function(eventName,callback, target){
		if(!this.subscribers) {this.subscribers=[]}
        if (!this.subscribers[eventName]) {
            this.subscribers[eventName] = [];}
        this.subscribers[eventName].push({name:eventName, func:callback});
    },
    
    dispatchEvent : function(eventName, data){
		var self=this;
        data = data ||{};
        var funcs = this.subscribers[eventName]||[];
   	        funcs.forEach(function(observer) { 
                observer.func.call(self, data); 
			});
    },
	
	isAuthenticated : function(callback){
		var lastRecordedToken = this.readTokenCookie(this.config.cookieName);
		if(lastRecordedToken){
			this.getInfo(lastRecordedToken, callback);
		}
		else {
			callback(false)
		}
	},
	
	addRequestHandler : function(callback){
		var id = this.requestID();
		this.listeners[id] = callback;
		return id;
	},
	
	getRequestHandler : function(id){
		return this.listeners[id]||function(){}
	},
	
	getInfo : function(tokenString, callback) {
		if(!this.config.devId) {
			throw new Error("OpenAuth#getInfo() - Invalid OpenAuth 'devId'. Unable to resolve a devId from window.config.devId.\ndevId=" + this.config.devId);
		};
		var reqId = this.addRequestHandler(callback||function(){});
		var requestUrl = "https://api.screenname.aol.com/auth/getInfo?a="+(tokenString)+"&devId="+this.config.devId+"&referer="+this.config.succUrl+"&f=json&c=OpenAuth.gotInfo&r="+ (reqId||"");
		this.infoJSONScript = new scriptJSON(requestUrl);
		this.infoJSONScript.buildScriptTag();
		this.infoJSONScript.addScriptTag();	
	},
	
	login : function(callback) {
		if(!this.config.devId) {
			throw new Error("OpenAuth#login() - Invalid OpenAuth 'devId'. Unable to resolve a devId from window.config.devId.\ndevId=" + this.config.devId);
		};
		var reqId = this.addRequestHandler(callback||function(){});
		var requestUrl = "http://api.screenname.aol.com/auth/login?supportedIdType=" + this.config.supportedIdType + "&devId="+(this.config.devId)+"&f=json&succUrl="+(this.config.succUrl)+"&r="+reqId;
//		var iframe = document.createElement("iframe");
//			iframe.style.width="530px";
//			iframe.style.height="310px";
//			iframe.style.position = "absolute";
//			iframe.style.top="0px";
//			iframe.style.left="0px";
//			iframe.setAttribute("frameborder",0); 
			//iframe.setAttribute("allowtransparency",true);
			//iframe.src= requestUrl;
//			document.body.appendChild(iframe);
			//var w = window.open(requestUrl);
			var x = (screen.width - 490)/2; var y = (screen.height -490)/2;	
			var w = window.open(requestUrl,'login','resizable=yes,width=515,height=300,directories=no,titlebar=no,status=no,menubar=no,toolbar=no,location=yes,left='+x+',top='+y);
			var t = setInterval(function(){
				try {
					var url = w.document.location.href; //iframe.contentDocument.location.href; //decodeURIComponent(iframe.contentDocument.location.href);
					if(url.indexOf(location.hostname)>= 0) {
						clearInterval(t);
						var token = this.parseLoginResponse_fromUrl(url);
//						iframe.style.display = "none";
//						iframe.parentNode.removeChild(iframe);
						w.close();
						if(token && token.response) {
							this.dispatchEvent("onloginattempt", token.response);
							var _callback = this.getRequestHandler(token.response.requestId);
								if (_callback) {
									_callback(token.response);
								}
							if(token.response.statusCode === 200) {
								if (!this.readTokenCookie(this.config.cookieName)) {
									this.createTokenCookie(this.config.cookieName, token.response.data.token.a, 1);
								}
								this.dispatchEvent("onlogin", token.response);
							}
							else if(token.response.statusCode === 401) {
								this.dispatchEvent("onloginfailure", token.response);
							}
						}
						else {
							this.dispatchEvent("onloginfailure", token.response);
						}
					}
				}catch(e){}
			}.bind(this), 400);
			
		return w;
	},
	
	gotInfo : function(httpResponse){
		var self=this;
		var userData = null;
		try {
			userData = httpResponse.response.data.userData;
			userData.loginId = this.normalize_loginIDs(userData.loginId);
		}
		catch(e){
			if (!userData || !userData.loginId) {
				var reloadit = confirm("Your login session has expired unexpectedly!. Would you like to try and reload this page?");
				if(reloadit) {
					self.logout(function(logout_response){
						if (self.hasToken()) {
							self.eraseTokenCookie(self.config.cookieName);}
						location.reload();
					});	
				}
			}
		};
		this.dispatchEvent("ongetinfo", httpResponse.response);
		this.getRequestHandler(httpResponse.response.requestId)(httpResponse.response);
	},
	
	parseOpenAuthResponse_fromUrl : function(url){
        var r = decodeURIComponent(url).split("res=")[1];
        r = r.replace("+", "", "g");
		return (r||{});
	},
	
	parseLoginResponse_fromUrl : function(url){
		/*var r = decodeURIComponent(url).split("res=")[1];
		r=r.replace("+","","g");
		r = JSON.parse(r);	
		return r||{};*/
		
		url = decodeURIComponent(url);
		//var url = decodeURIComponent("http://localhost:8082/dashboard/loggedIn.jsp?res=%7B%22response%22%3A+%7B%22statusCode%22%3A+200%2C+%22requestId%22%3A+%2224797991255482222252%22%2C+%22data%22%3A+%7B%22token%22%3A+%7B%22expiresIn%22%3A+86400%2C+%22a%22%3A+%22%252FwQAAAAAAADW0bF6cTBLct%252B91B%252BEiD53TF50SNW%252FBqCp8hwa9xw9BHeSIzBu4lD8rao4oJRRmn8YWkrmDcHoBl2gx3y%252B5HNIEUYCsqFqvjgir%252FjI6549eQS6hsAk3K3tG%252BMa1OlYKFJJexwRvJ37z7qwYW0%253D%22%7D%7D%2C+%22statusText%22%3A+%22OK%22%7D%7D");
		url = url.split("res=")[1];
		url=url.replace(/\+/ig,"");
		var token = JSON.parse(url);
		return token||{};
	},
	
	logout : function (callback) {
		var reqId = this.addRequestHandler(callback||function(){});
		var logouturl = "https://api.screenname.aol.com/auth/logout?devId=" + this.config.devId + "&a=" + this.hasToken() + "&c=OpenAuth.loggedOut&doSNSLogout=1&f=json&r=" + reqId;
		this.infoJSONScript = new scriptJSON(logouturl);
		this.infoJSONScript.buildScriptTag();
		this.infoJSONScript.addScriptTag();	
	},
	
	loggedOut : function(httpResponse) {
		if(httpResponse.response.statusCode == 200) {
			if (this.hasToken()) {
				this.eraseTokenCookie(this.config.cookieName);
			}
		};
		this.getRequestHandler(httpResponse.response.requestId)(httpResponse.response);
	},
	
	hasToken : function(){
		return this.readTokenCookie(this.config.cookieName);
	},
	
	getToken : function(callback) {	
		if(this.hasToken()) {return this.hasToken()};
		
		var reqId = this.addRequestHandler(callback);
		var requestUrl = "https://api.screenname.aol.com/auth/getToken?devId="+this.config.devId+"&f=json&c=OpenAuth.gotToken&r="+reqId;
		this.tokenJSONScript = new scriptJSON(requestUrl);
		this.tokenJSONScript.buildScriptTag();
		this.tokenJSONScript.addScriptTag();
	},
	
	gotToken : function(httpResponse) {
		this.getRequestHandler(httpResponse.response.requestId)(httpResponse.response);
	},
	
	createTokenCookie : function (name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	},
	
	readTokenCookie : function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			if (c.indexOf(nameEQ) == 0) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	},
	
	eraseTokenCookie : function(name) {
		this.createTokenCookie(name,"",-1);
	},
	
	listeners : {},
	
	subscribers : [],
	
	normalize_loginIDs : function(loginId){ /*internal*/
		if(!loginId) {throw new Error("OpenAuth#__normalize_login_ids(loginId) expected a loginId string.")};
		/* Normalize GMAIL*/
		if(loginId.indexOf("www.google.com/")>=0 && loginId.indexOf("id?id=") >=0) {
			    loginId = loginId.split(/id\?id\=/)[1];
				return loginId;
		}
		else {
			return loginId;
		}
	}
};